package view.admin;

import controller.ReservationController;
import model.Reservation;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import java.util.Comparator;
import java.util.List;

/**
 * 预约管理面板
 */
public class ReservationManagementPanel extends JPanel {
    private ReservationController reservationController;

    private JTable reservationTable;
    private DefaultTableModel tableModel;
    private TableRowSorter<DefaultTableModel> tableSorter;
    private JButton cancelReservationButton;
    private JButton refreshButton;
    private JComboBox<String> dateFilterComboBox;
    private JComboBox<String> statusFilterComboBox;
    private JTextField searchField;
    private JButton searchButton;

    public ReservationManagementPanel() {
        this.reservationController = new ReservationController();

        initComponents();
        setupLayout();
        setupEventListeners();
        refreshData();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        setBackground(new Color(248, 250, 252)); // 设置背景色与其他管理页面一致

        // 表格列名
        String[] columnNames = { "预约ID", "学号", "姓名", "座位号", "楼层", "预约日期",
                "开始时间", "结束时间", "状态", "预约时间" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        reservationTable = new JTable(tableModel);
        reservationTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        reservationTable.setRowHeight(25);

        // 添加排序功能
        tableSorter = new TableRowSorter<>(tableModel);
        reservationTable.setRowSorter(tableSorter);

        // 配置表头样式，显示排序指示器
        JTableHeader header = reservationTable.getTableHeader();
        header.setFont(new Font("Microsoft YaHei", Font.BOLD, 12));
        header.setBackground(new Color(243, 244, 246));
        header.setForeground(new Color(75, 85, 99));
        header.setReorderingAllowed(false);

        // 简化排序配置，让系统自动处理
        // setupColumnComparators();

        // 设置列宽
        reservationTable.getColumnModel().getColumn(0).setPreferredWidth(80);
        reservationTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        reservationTable.getColumnModel().getColumn(2).setPreferredWidth(100);
        reservationTable.getColumnModel().getColumn(3).setPreferredWidth(80);
        reservationTable.getColumnModel().getColumn(4).setPreferredWidth(60);
        reservationTable.getColumnModel().getColumn(5).setPreferredWidth(100);
        reservationTable.getColumnModel().getColumn(6).setPreferredWidth(80);
        reservationTable.getColumnModel().getColumn(7).setPreferredWidth(80);
        reservationTable.getColumnModel().getColumn(8).setPreferredWidth(80);
        reservationTable.getColumnModel().getColumn(9).setPreferredWidth(120);

        // 按钮
        cancelReservationButton = new JButton("取消预约");
        refreshButton = new JButton("刷新");
        searchButton = new JButton("搜索");

        searchField = new JTextField(15);

        cancelReservationButton.setEnabled(false);

        // 筛选器
        dateFilterComboBox = new JComboBox<>();
        dateFilterComboBox.addItem("全部日期");
        dateFilterComboBox.addItem("今天");
        dateFilterComboBox.addItem("明天");
        dateFilterComboBox.addItem("本周");

        statusFilterComboBox = new JComboBox<>();
        statusFilterComboBox.addItem("全部状态");
        statusFilterComboBox.addItem("有效");
        statusFilterComboBox.addItem("已取消");
        statusFilterComboBox.addItem("已完成");
    }

    private void setupLayout() {
        // 顶部工具栏 - 现代化白色卡片样式
        JPanel toolPanel = new JPanel();
        toolPanel.setLayout(new BoxLayout(toolPanel, BoxLayout.Y_AXIS));
        toolPanel.setBackground(new Color(255, 255, 255));
        toolPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));

        // 工具栏标题
        JLabel titleLabel = createStyledLabel("预约管理", Font.BOLD, 18, new Color(55, 65, 81));
        toolPanel.add(titleLabel);
        toolPanel.add(Box.createVerticalStrut(15));

        // 筛选、搜索和操作按钮区域 - 单行布局
        JPanel controlRow = new JPanel(new BorderLayout());
        controlRow.setBackground(new Color(255, 255, 255));

        // 左侧：筛选和搜索区域
        JPanel leftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        leftPanel.setBackground(new Color(255, 255, 255));

        leftPanel.add(createStyledLabel("搜索:", Font.PLAIN, 14, new Color(107, 114, 128)));
        leftPanel.add(Box.createHorizontalStrut(8));
        styleTextField(searchField);
        searchField.setPreferredSize(new Dimension(180, 35));
        leftPanel.add(searchField);
        leftPanel.add(Box.createHorizontalStrut(10));
        styleButton(searchButton);
        leftPanel.add(searchButton);
        leftPanel.add(Box.createHorizontalStrut(25));

        leftPanel.add(createStyledLabel("日期:", Font.PLAIN, 14, new Color(107, 114, 128)));
        leftPanel.add(Box.createHorizontalStrut(8));
        styleComboBox(dateFilterComboBox);
        leftPanel.add(dateFilterComboBox);
        leftPanel.add(Box.createHorizontalStrut(25));

        leftPanel.add(createStyledLabel("状态:", Font.PLAIN, 14, new Color(107, 114, 128)));
        leftPanel.add(Box.createHorizontalStrut(8));
        styleComboBox(statusFilterComboBox);
        leftPanel.add(statusFilterComboBox);

        // 右侧：操作按钮区域
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        rightPanel.setBackground(new Color(255, 255, 255));

        styleButton(refreshButton);
        styleButton(cancelReservationButton);

        rightPanel.add(refreshButton);
        rightPanel.add(Box.createHorizontalStrut(10));
        rightPanel.add(cancelReservationButton);

        controlRow.add(leftPanel, BorderLayout.WEST);
        controlRow.add(rightPanel, BorderLayout.EAST);

        toolPanel.add(controlRow);

        // 容器面板，添加边距
        JPanel topContainer = new JPanel(new BorderLayout());
        topContainer.setBackground(new Color(248, 250, 252));
        topContainer.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        topContainer.add(toolPanel, BorderLayout.CENTER);

        // 表格面板 - 现代化样式
        JPanel tableContainer = new JPanel(new BorderLayout());
        tableContainer.setBackground(new Color(248, 250, 252));
        tableContainer.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));

        styleTable(reservationTable);
        JScrollPane scrollPane = new JScrollPane(reservationTable);
        scrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(0, 0, 0, 0)));
        scrollPane.setBackground(new Color(255, 255, 255));
        scrollPane.getViewport().setBackground(new Color(255, 255, 255));

        tableContainer.add(scrollPane, BorderLayout.CENTER);

        add(topContainer, BorderLayout.NORTH);
        add(tableContainer, BorderLayout.CENTER);
    }

    private void setupEventListeners() {
        refreshButton.addActionListener(_ -> refreshData());

        dateFilterComboBox.addActionListener(_ -> refreshData());
        statusFilterComboBox.addActionListener(_ -> refreshData());

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleSearch();
            }
        });

        searchField.addActionListener(_ -> handleSearch());

        cancelReservationButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cancelSelectedReservation();
            }
        });

        // 表格选择事件
        reservationTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                int selectedRow = reservationTable.getSelectedRow();
                if (selectedRow >= 0) {
                    String status = (String) tableModel.getValueAt(selectedRow, 8);
                    cancelReservationButton.setEnabled("有效".equals(status));
                } else {
                    cancelReservationButton.setEnabled(false);
                }
            }
        });
    }

    public void refreshData() {
        try {
            // 获取筛选条件
            String dateFilter = (String) dateFilterComboBox.getSelectedItem();
            String statusFilter = (String) statusFilterComboBox.getSelectedItem();

            List<Reservation> reservations = reservationController.getFilteredReservations(dateFilter, statusFilter);

            // 清空表格
            tableModel.setRowCount(0);

            // 填充数据
            for (Reservation reservation : reservations) {
                Object[] row = {
                        reservation.getReservationId(),
                        reservation.getUser() != null ? reservation.getUser().getStudentId() : "N/A",
                        reservation.getUser() != null ? reservation.getUser().getName() : "N/A",
                        reservation.getSeat() != null ? reservation.getSeat().getSeatNumber() : "N/A",
                        reservation.getSeat() != null ? reservation.getSeat().getFloor() + "楼" : "N/A",
                        reservation.getReservationDate(),
                        reservation.getStartTime(),
                        reservation.getEndTime(),
                        reservation.getStatusText(),
                        reservation.getCreateTime().toString().substring(0, 16)
                };
                tableModel.addRow(row);
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载预约信息失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void handleSearch() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            refreshData();
            return;
        }

        try {
            List<Reservation> reservations = reservationController.searchReservations(keyword);

            // 清空表格
            tableModel.setRowCount(0);

            // 填充搜索结果
            for (Reservation reservation : reservations) {
                Object[] row = {
                        reservation.getReservationId(),
                        reservation.getUser() != null ? reservation.getUser().getStudentId() : "N/A",
                        reservation.getUser() != null ? reservation.getUser().getName() : "N/A",
                        reservation.getSeat() != null ? reservation.getSeat().getSeatNumber() : "N/A",
                        reservation.getSeat() != null ? reservation.getSeat().getFloor() + "楼" : "N/A",
                        reservation.getReservationDate(),
                        reservation.getStartTime(),
                        reservation.getEndTime(),
                        reservation.getStatusText(),
                        reservation.getCreateTime().toString().substring(0, 16)
                };
                tableModel.addRow(row);
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "搜索失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void cancelSelectedReservation() {
        int selectedRow = reservationTable.getSelectedRow();
        if (selectedRow < 0)
            return;

        int reservationId = (Integer) tableModel.getValueAt(selectedRow, 0);
        String studentId = (String) tableModel.getValueAt(selectedRow, 1);
        String seatNumber = (String) tableModel.getValueAt(selectedRow, 3);

        int option = JOptionPane.showConfirmDialog(this,
                "确定要取消学号为 " + studentId + " 的座位 " + seatNumber + " 的预约吗？",
                "确认取消", JOptionPane.YES_NO_OPTION);

        if (option == JOptionPane.YES_OPTION) {
            try {
                boolean success = reservationController.cancelReservation(reservationId);

                if (success) {
                    JOptionPane.showMessageDialog(this, "预约已取消!", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshData();
                } else {
                    JOptionPane.showMessageDialog(this, "取消预约失败!", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "取消预约失败: " + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 创建样式化标签
     */
    private JLabel createStyledLabel(String text, int style, int size, Color color) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", style, size));
        label.setForeground(color);
        return label;
    }

    /**
     * 样式化表格
     */
    private void styleTable(JTable table) {
        table.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        table.setRowHeight(35);
        table.setSelectionBackground(new Color(219, 234, 254));
        table.setSelectionForeground(new Color(30, 58, 138));
        table.setGridColor(new Color(229, 231, 235));
        table.setShowGrid(true);
        table.setIntercellSpacing(new Dimension(1, 1));

        // 表头样式
        table.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        table.getTableHeader().setBackground(new Color(249, 250, 251));
        table.getTableHeader().setForeground(new Color(75, 85, 99));
        table.getTableHeader().setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(229, 231, 235)));
    }

    /**
     * 样式化按钮
     */
    private void styleButton(JButton button) {
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBackground(new Color(59, 130, 246));
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(37, 99, 235), 1),
                BorderFactory.createEmptyBorder(8, 16, 8, 16)));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));
        button.setPreferredSize(new Dimension(button.getPreferredSize().width, 35));

        // 添加悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent e) {
                button.setBackground(new Color(37, 99, 235));
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent e) {
                button.setBackground(new Color(59, 130, 246));
            }
        });
    }

    /**
     * 样式化文本框
     */
    private void styleTextField(JTextField field) {
        field.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        field.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        field.setBackground(new Color(255, 255, 255));
        field.setPreferredSize(new Dimension(field.getPreferredSize().width, 35));

        // 添加焦点效果
        field.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                field.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(59, 130, 246), 2),
                        BorderFactory.createEmptyBorder(7, 11, 7, 11)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                field.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                        BorderFactory.createEmptyBorder(8, 12, 8, 12)));
            }
        });
    }

    /**
     * 样式化下拉框
     */
    private void styleComboBox(JComboBox<String> comboBox) {
        comboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        comboBox.setBackground(new Color(255, 255, 255));
        comboBox.setBorder(BorderFactory.createLineBorder(new Color(209, 213, 219), 1));
        comboBox.setPreferredSize(new Dimension(120, 35));
        comboBox.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }

    /**
     * 设置表格列的排序比较器
     */
    private void setupColumnComparators() {
        // 预约ID列 - 数字排序
        tableSorter.setComparator(0, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                try {
                    return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2));
                } catch (NumberFormatException e) {
                    return o1.compareTo(o2);
                }
            }
        });

        // 学号列 - 字符串排序
        tableSorter.setComparator(1, String.CASE_INSENSITIVE_ORDER);

        // 姓名列 - 字符串排序
        tableSorter.setComparator(2, String.CASE_INSENSITIVE_ORDER);

        // 座位号列 - 自然排序
        tableSorter.setComparator(3, String.CASE_INSENSITIVE_ORDER);

        // 楼层列 - 数字排序
        tableSorter.setComparator(4, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                try {
                    return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2));
                } catch (NumberFormatException e) {
                    return o1.compareTo(o2);
                }
            }
        });

        // 预约日期列 - 日期排序
        tableSorter.setComparator(5, String.CASE_INSENSITIVE_ORDER);

        // 开始时间列 - 时间排序
        tableSorter.setComparator(6, String.CASE_INSENSITIVE_ORDER);

        // 结束时间列 - 时间排序
        tableSorter.setComparator(7, String.CASE_INSENSITIVE_ORDER);

        // 状态列 - 状态优先级排序
        tableSorter.setComparator(8, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return getStatusPriority(o1) - getStatusPriority(o2);
            }

            private int getStatusPriority(String status) {
                switch (status) {
                    case "有效":
                        return 1;
                    case "已完成":
                        return 2;
                    case "已取消":
                        return 3;
                    default:
                        return 999;
                }
            }
        });

        // 预约时间列 - 时间戳排序
        tableSorter.setComparator(9, String.CASE_INSENSITIVE_ORDER);
    }
}
